package com.lancoo.answer.component

import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import androidx.annotation.RequiresApi
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.databinding.ObservableArrayList
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lancoo.answer.R
import com.lancoo.answer.databinding.EvViewItemOptionBinding
import com.lancoo.answer.helper.recyclerview.BindingViewAdapter
import com.lancoo.answer.helper.recyclerview.BindingViewHolder
import com.lancoo.answer.helper.recyclerview.SingleTypeAdapter
import com.lancoo.answer.model.ConstantBean
import com.lancoo.answer.model.ConstantBean.Companion.taskState
import com.lancoo.answer.model.TaskState
import com.lancoo.answer.model.bean.Child
import com.lancoo.answer.model.bean.ChildOption
import com.lancoo.answer.model.bean.EvOptionBean
import com.lancoo.answer.model.eventBean.CompleteCurrentAnsPointEventBean
import com.lancoo.answer.util.CustomPictureTextViewUtil
import com.lancoo.answer.util.ExamFontSizeAdjustUtils
import com.lancoo.answer.util.RichTxtDealTuils
import com.lancoo.answer.util.ScaleUtil.addClickScale
import com.lancoo.answer.view.fragment.option.adapter.ItemPresenter
import com.lancoo.answer.widget.audioPlayView.AudioPlayCallBack
import com.lancoo.answer.widget.combinationView.QueseBodyView
import org.greenrobot.eventbus.EventBus

/**
 * Created by Dadong on 2021/12/7
 * Describe: 选择作答控件
 * 返回选择的选项 小题抽题
 */
class OptionComponent : ConstraintLayout, BindingViewAdapter.ItemDecorator, ItemPresenter {
    private lateinit var rvOption: RecyclerView
    private lateinit var tvChild: QueseBodyView
    private var optionList = ObservableArrayList<EvOptionBean>()
    private var callback: OptionCallback? = null
    private lateinit var child: Child
    private var childIndex = 0

    private var clickEnable = true
    private var chooseColorDeep = false
    private var multiable = false

    constructor(context: Context) : super(context) {
        initView(context)
    }

    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {
        initView(context)
    }

    constructor(context: Context, attributeSet: AttributeSet, defStyleAttr: Int) : super(
        context,
        attributeSet,
        defStyleAttr
    ) {
        initView(context)
    }

    private fun initView(context: Context) {
        LayoutInflater.from(context).inflate(R.layout.ev_view_option, this, true)
        rvOption = findViewById(R.id.option_rv)
        tvChild = findViewById(R.id.tv_child)
        if (taskState == TaskState.LOOKING || taskState == TaskState.ORIGINAL) {
            clickEnable = false
        }
        initAdapter()
    }

    private val mAdapter: SingleTypeAdapter<EvOptionBean> by lazy {
        SingleTypeAdapter(context, R.layout.ev_view_item_option, optionList)
    }

    private fun initAdapter() {
        rvOption.adapter = mAdapter.apply {
            itemPresenter = this@OptionComponent
            itemDecorator = this@OptionComponent
        }
        val linearLayoutManager = LinearLayoutManager(context)
        rvOption.layoutManager = linearLayoutManager.apply {
            orientation = LinearLayoutManager.VERTICAL
        }
    }

    fun updateCheck(optionIndex: String) {
        optionList.forEach {
            if (optionIndex == it.OptionIndex) {
                it.SelectState = 2
            }
        }
    }

    fun resetState() {
        optionList.forEach { it.SelectState = 0 }
    }

    //是否允许多选
    fun enableMultiable(enable: Boolean) {
        multiable = enable
    }

    //ask 和 音频都为空 ，显示序号
    //屏蔽tvChild
    override fun decorator(
        holder: BindingViewHolder<ViewDataBinding>?,
        position: Int,
        viewType: Int
    ) {
        val itemBinding: EvViewItemOptionBinding = holder!!.binding as EvViewItemOptionBinding
        itemBinding.btnOption1.addClickScale()
        if (!clickEnable) {
            itemBinding.btnOption1.visibility = View.GONE
            itemBinding.tvOption1.visibility = View.VISIBLE
        } else {
            itemBinding.btnOption1.visibility = View.VISIBLE
            itemBinding.tvOption1.visibility = View.GONE
        }
        if (child.ChildAsk.isNullOrEmpty()) {
            RichTxtDealTuils.getNormalChildBody( itemBinding.tvIndex,child,false)
            if (position == 0) {
                itemBinding.tvIndex.visibility = View.VISIBLE
            } else {
                itemBinding.tvIndex.visibility = View.INVISIBLE
            }
        } else {
            itemBinding.tvIndex.visibility = View.GONE
        }

        CustomPictureTextViewUtil(context, itemBinding.tvContent, itemBinding.item!!.Option)
        when (itemBinding.item!!.SelectState) {
            0 -> {
                itemBinding.btnOption1.setBackgroundResource(R.mipmap.ev_icon_choice_white)
                itemBinding.btnOption1.setTextColor(context.resources.getColor(R.color.c333333))
            }
            1 -> {
                itemBinding.btnOption1.setBackgroundResource(R.mipmap.ev_icon_choice_blue)
                itemBinding.btnOption1.setTextColor(context.resources.getColor(R.color.cffffff))
            }
            2 -> {
                if (chooseColorDeep) {
                    itemBinding.btnOption1.setBackgroundResource(R.mipmap.ev_icon_choice_blue)
                } else {
                    itemBinding.btnOption1.setBackgroundResource(R.mipmap.ev_icon_choice_light_blue)
                }
                itemBinding.btnOption1.setTextColor(context.resources.getColor(R.color.cffffff))
            }
        }
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(itemBinding.tvIndex,14)
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(itemBinding.tvContent,14)
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(itemBinding.tvOption1,15)
    }


    fun setChild(child: Child) {
        this.child = child
        tvChild.initData(child)
        if (child.ChildAsk.isNullOrEmpty()) {
            setTvChildVisibility(View.GONE)
        }
        setOptionList(child.ChildOptionList!!)
    }

    fun setChildIndex(index: Int) {
        this.childIndex = index;
    }

    fun setTvChildVisibility(visible: Int) {
        tvChild.visibility = visible
    }

    private fun setOptionList(optionList: ArrayList<ChildOption>) {
        this.optionList.clear()
        optionList.forEachIndexed { index, it ->
            val option = EvOptionBean().apply {
                Option = it.Option
                OptionIndex = it.OptionIndex
            }
            this.optionList.add(option)
        }

        child.ItemList!!.forEach { item ->
            this.optionList.forEach { childOption ->
                if (item.StuAnswer == childOption.OptionIndex) {
                    childOption.SelectState = 2
                }
            }
        }
        mAdapter.notifyDataSetChanged()
    }

    private var lastClickTime: Long = 0
    fun isFastDoubleClick(): Boolean {
        val time = System.currentTimeMillis()
        val timeD = time - lastClickTime
        if (lastClickTime > 0 && timeD < 500) {
            Log.v("isFastDoubleClick", "短时间内按钮多次触发")
            return true
        }
        lastClickTime = time
        return false
    }

    //设置选中后的颜色是深还是浅
    fun setChooseColorDeep(colorDeep: Boolean) {
        this.chooseColorDeep = colorDeep
    }

    //设置选中后的颜色是深还是浅
    fun hideQuesBody() {
        tvChild.visibility = View.GONE
    }

    fun setCallback(callback: OptionCallback) {
        this.callback = callback
    }

    interface OptionCallback {
        fun clickCallback(item: EvOptionBean)
    }

    fun pause() {
        tvChild.pause()
    }

    fun release() {
        tvChild.release()
        callback = null
    }

    fun setPlayCallBack(callBack: AudioPlayCallBack) {
        tvChild.setCallBack(callBack)
    }

    fun changeUIStyle() {
        tvChild.changeUIStyle()
    }

    fun enableAnswer(enable: Boolean) {
        clickEnable = enable
    }

    override fun onItemClick(v: View, item: EvOptionBean) {
        if (isFastDoubleClick() || !clickEnable) {
            return
        }
        if (ConstantBean.taskControlBean!!.enableAnwer == 0) {
            clickEnable = false
//            mAdapter.notifyDataSetChanged()
            return
        } else {
            clickEnable = true
        }
        if (!multiable)
            resetState()
        if (callback == null) {
            child.ItemList!![0].StuAnswer = item.OptionIndex
        }
        EventBus.getDefault().post(item.apply {
            this.ChildIndex = childIndex
        })
        callback?.clickCallback(item)
        mAdapter.notifyDataSetChanged()
        item.SelectState = 1
        handler.postDelayed({
            item.SelectState = 2
            mAdapter.notifyDataSetChanged()
            EventBus.getDefault().post(CompleteCurrentAnsPointEventBean())
        }, 200)
    }

    fun adjustFontSize(){
        tvChild.adjustFontSize()
        mAdapter.notifyDataSetChanged()
    }

    fun markQuestion(){
        tvChild.markQuestion()
        mAdapter.notifyDataSetChanged()
    }
}